<?php

namespace app\service;

use app\enum\UserCode;
use app\enum\WxShopCode;
use app\model\Agent;
use app\model\CarQrcode;
use app\model\PhoneDn;
use app\model\User;
use app\model\UserReward;
use app\model\UserScan;
use app\model\WechatMessage;
use Exception;
use library\temp_img;
use library\wechat;
use library\wx_pay;
use library\youyin;
use support\Log;
use Tinywan\Jwt\JwtToken;

class UserService extends Base
{
    //登录
    public function toLoginByCode($code, $platform, $nickname, $avatar): array
    {
        //获取微信小程序的openid
        switch ($platform) {
            case UserCode::PLATFORM['测试']:
                $openid = $code;
                break;
            case UserCode::PLATFORM['微信']:
                [$openid, $unionid] = (new wechat())->get_openid($code);
                break;
            default:
                return apiError('平台错误');
        }
        //查询会员信息
        $user = User::where(['openid' => $openid])->find();
        if (empty($user)) {
            if (!empty($unionid)) {
                //先查询unionid是否存在
                $user = User::where(['unionid' => $unionid])->find();
            }
            if (!empty($user)) {
                $user->openid = $openid;
                $user->save();
            } else {
                //注册
                $param = [
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'platform' => $platform,
                    'join_ip' => request()->header()['x-real-ip'],
                    'join_time' => date('Y-m-d H:i:s'),
                    'status' => UserCode::STATUS_NORMAL,
                ];
                //注册成功
                $user = new User();
                $user->save($param);
            }

        }
        if ($user['status'] == UserCode::STATUS_DISABLE) {
            return apiError('该账号已停用');
        }
        $user->save();

        $extend = [
            'id' => $user['id'],
            'name' => '云动挪车',
            'access_exp' => 864000000,  // 100天
            'refresh_exp' => 864000000,  // 100天
            'client' => JwtToken::TOKEN_CLIENT_MOBILE
        ];
        $generateToken = JwtToken::generateToken($extend);

        if ($generateToken) {
            $data = ['token' => $generateToken['access_token'], 'user_info' => self::info($user)];
            return apiSuccess($data);
        }
        return apiError('失败');

    }

    public static function info(User $user)
    {
        $user = User::with('carQrcode')->where(['id' => $user->id])->find();
        // $user->qrcode_url = 'https://' . env('DOMAIN_NAME') . '/qrcode/wxa_t/' . $user->id . '.png';
        $user->qrcode_url = 'https://' . env('DOMAIN_NAME') . '/qrcode/temp/' . $user->id . '.jpeg';
        $user->group_img = 'https://' . env('DOMAIN_NAME') . '/qrcode/wxa/12.png';
        //可提现金额
        $user->can_withdraw = UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['待提现'])->sum('amount');
        //不足两位小数时补全
        $user->can_withdraw = sprintf("%.2f", $user->can_withdraw);
        //待入账金额
        $user->pending_amount = UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['待入账'])->sum('amount');
        //不足两位小数时补全
        $user->pending_amount = sprintf("%.2f", $user->pending_amount);

        //用户引流奖励金
        if ($user->is_agent) {
            $user->reward_title = '其他用户首次通过您的推广码打开小程序后，系统将自动绑定双方关系。';
            //奖励金规则按钮开关
            $user->reward_switch = 0;
        } else {
            //奖励金规则按钮开关
            $user->reward_switch = 1;
            $user->reward_title = '其他用户首次通过您的挪车码打开小程序后，系统将自动绑定双方关系。';
        }
        $user->reward_text = '如果该用户随后下单购买挪车码，您将获得';
        $user->reward_money = '5.00';


        $user->agent_tip_text1 = "您邀请的下级用户（一级代理）购买挪车码代理，您可获得佣金";
        $user->agent_tip_money1 = "10.00";
        $user->agent_tip_text2 = "您的下级用户发展出的二级代理购买挪车码代理，您可获得佣金";
        $user->agent_tip_money2 = "5.00";


        return $user;
    }

    public function update_info(User $user, $nickname, $avatar)
    {
        !empty($nickname) && $user->nickname = $nickname;
        !empty($avatar) && $user->avatar = $avatar;
        $user->save();
        $user = self::info($user);
        return apiSuccess($user);
    }


    //变更微信消息通知状态
    public function change_wx_notice(User $user, $wx_notice)
    {

        if ($wx_notice == 1) {
            $msg = '开启成功';
        } else if ($wx_notice == 0) {
            $msg = '关闭成功';
        } else {
            return apiError('参数错误');
        }


        $user->wx_notice = $wx_notice;
        $user->save();
        $user = self::info($user);


        return apiSuccess($user, $msg);
    }

    //获取该小程序码详情
    public function get_qrcode_details($qrcode_id)
    {
        $qrcode = CarQrcode::with('wxNotice')->find($qrcode_id);
        if (!$qrcode) {
            return apiError('二维码不存在');
        }
        return apiSuccess($qrcode);
    }


    //修改小程序码
    public function update_qrcode(User $user, $from)
    {
        if (empty($from)) {
            return apiError('参数不能为空');
        }

        $qrcode_id = $from['qrcode_id'];

        $qrcode = CarQrcode::find($qrcode_id);
        if (!$qrcode) {
            return apiError('挪车码不存在');
        }

        if ($qrcode->status != UserCode::QRCODE_STATUS['使用中']) {
            return apiError('挪车码已失效');
        }

        if ($qrcode->user_id != $user->id) {
            return apiError('该挪车码已被绑定');
        }

        //检测手机号是否正常
        if (isset($from['phone']) && !preg_match('/^1[3456789]\d{9}$/', $from['phone'])) {
            return apiError('主手机号格式错误');
        }
        //检测备用手机号是否正常
        if (isset($from['backup_phone']) && !preg_match('/^1[3456789]\d{9}$/', $from['backup_phone'])) {
            return apiError('副手机号格式错误');
        }
        $from['id'] = $qrcode_id;
        $qrcode->save($from);
        return apiSuccess($qrcode);
    }


    public function bind_qrcode(User $user, $from)
    {
        if (empty($from)) {
            return apiError('参数不能为空');
        }

        $qrcode_id = $from['qrcode_id'];

        $qrcode = CarQrcode::find($qrcode_id);
        if (!$qrcode) {
            return apiError('挪车码不存在');
        }

        if ($qrcode->status == UserCode::QRCODE_STATUS['未生成']) {
            return apiError('挪车码未生效');
        }

        if ($qrcode->status == UserCode::QRCODE_STATUS['使用中']) {
            return apiError('其他用户已绑定该挪车码');
        }


        if ($qrcode->status !== UserCode::QRCODE_STATUS['待使用']) {
            return apiError('挪车码已禁用');
        }

        if ($qrcode->user_id) {
            return apiError('该挪车码已被绑定');
        }

        //检测手机号是否正常
        if (isset($from['phone']) && !preg_match('/^1[3456789]\d{9}$/', $from['phone'])) {
            return apiError('主手机号格式错误');
        }
        //检测备用手机号是否正常
        if (isset($from['backup_phone']) && !preg_match('/^1[3456789]\d{9}$/', $from['backup_phone'])) {
            return apiError('副手机号格式错误');
        }
        $from['id'] = $qrcode_id;
        $from['user_id'] = $user->id;
        $from['status'] = UserCode::QRCODE_STATUS['使用中'];
        $qrcode->save($from);

        $qrcode->wx_notice = $user->wx_notice;

        return apiSuccess($qrcode);
    }

    //绑定挪车吗
    public function unbind_qrcode(User $user, $qrcode_id)
    {
        $qrcode = CarQrcode::find($qrcode_id);
        if (!$qrcode) {
            return apiError('挪车码不存在');
        }

        if ($qrcode->status != UserCode::QRCODE_STATUS['使用中']) {
            return apiError('挪车码已失效');
        }
        if ($qrcode->user_id != $user->id) {
            return apiError('该挪车码已被绑定');
        }

        $qrcode->user_id = null;
        $qrcode->status = 1;
        $qrcode->phone = null;
        $qrcode->backup_phone = null;
        $qrcode->is_privacy = 1;
        $qrcode->short_message = 0;
        $qrcode->save();

        $user = self::info($user);
        return apiSuccess($user);
    }


    //绑定手机号
    public function bind_phone(User $user, $phone)
    {
        try {
            // 判断是否已绑定
            $existing = PhoneDn::where('phone', $phone)->find();
            if ($existing) {
                // 更新失效时间
                $existing->updated_at = date('Y-m-d H:i:s');
                $existing->save();
                return apiSuccess(['phone' => env('YOUYIN_ACCOUNT') . ',' . $existing->dn]);
            }

            // 没有绑定，重新分配
            $dn = DnService::allocateDn();
            $res = (new youyin())->bind($phone, $dn);

            if ($res['code'] === 1) {
                return apiSuccess(['phone' => env('YOUYIN_ACCOUNT') . ',' . $dn]);
            } else {
                DnService::releaseDn($dn);
                Log::error('绑定分机号失败: ' . $res['msg']);
                return apiSuccess(['phone' => $phone]);
            }

        } catch (\Throwable $e) {
            if (isset($dn)) {
                try {
                    DnService::releaseDn($dn);
                } catch (\Throwable $e) {
                    Log::error('释放分机号异常: ' . $e->getMessage());
                }
            }
            Log::error('绑定分机号异常: ' . $e->getMessage());
            return apiSuccess(['phone' => $phone]);
        }
    }


    //发送订阅消息
    public function send_subscribe_message(User $user, $send_data)
    {
        $templateId = env('WECHAT_TEMPLATE');
        $to_user = User::where('id', $send_data['to_user_id'])->find();

        if (!$to_user) {
            return apiError('用户不存在');
        }
        $openid = $to_user->openid;

        if (!empty($send_data['send_msg'])) {
            $res = wechat::get_sensitive_words($user->openid, $send_data['send_msg']);
            if (isset($res['errcode']) && $res['errcode'] == 0) {
                if ($res['result']['suggest'] !== 'pass') {
                    return apiError('消息包含违禁词汇，请重新输入');
                }
            } else {
                return apiError('消息推送失败,请使用其他方式联系车主！');
            }
        }

        //先判断发送限制
        $wechat_message_count = WechatMessage::where('from_user_id', $user->id)->where('to_user_id', $send_data['to_user_id'])->where('created_at', '>', date('Y-m-d H:i:s', time() - 86400))->count();

        if ($wechat_message_count >= 100) {
            return apiError('订阅消息24小时内只能发送一次哦~');
        }

        $data = [
            'thing2' => ['value' => $send_data['address']],
            'time3' => ['value' => date('Y-m-d H:i:s')],
            'thing4' => ['value' => '点击进入,可查看对方留言'],
        ];

        $to_user->wx_notice = 0;
        $to_user->save();

        $wechat_message = WechatMessage::create($send_data);
        $page = 'pages/yd_map/home?message_id=' . $wechat_message->id;
        $res = wechat::send_message($openid, $templateId, $page, $data);


        //如果消息发送失败
        if ($res['errcode'] != 0) {
            return apiError('订阅消息推送失败,请尝试其他方式联系车主~');
        } else {
            return apiSuccess($res, '消息发送成功,请等待车主回复~');
        }
    }

    //生成体验码
    public function create_experience_qrcode(User $user, $from)
    {
        //检测手机号是否正常
        if (isset($from['phone']) && !preg_match('/^1[3456789]\d{9}$/', $from['phone'])) {
            return apiError('主手机号格式错误');
        }

        if (!empty($from['backup_phone'])) {
            //检测备用手机号是否正常
            if (!preg_match('/^1[3456789]\d{9}$/', $from['backup_phone'])) {
                return apiError('副手机号格式错误');
            }
        }

        $user->phone = $from['phone'];
        $user->backup_phone = $from['backup_phone'];
        $user->is_privacy = $from['is_privacy'];
        $user->is_bind = 1;
        $user->save();
        $path = 'wxa_t';
        $real_url = "/qrcode/{$path}/{$user->id}.png";
        if (!file_exists(public_path() . $real_url)) {
            $access_token = wechat::get_access_token();
            wechat::get_wxa_code($access_token, $user->id, 'user_id', $path);
            try {
                temp_img::mergeImages(
                    public_path() . '/temp.jpg',           // 背景图
                    public_path() . $real_url,         // 叠加图
                    public_path() . '/qrcode/temp/' . $user->id . '.jpeg',       // 输出图
                    88, 230,            // 合成位置 (x, y)
                    100, 100            // 前景图缩放宽高（可省略）
                );
                echo "图片合成成功！";
            } catch (Exception $e) {
                echo "图片合成失败：" . $e->getMessage();
            }
        }


        $user = self::info($user);
        return apiSuccess($user);
    }

    public function unbind_experience_qrcode(User $user)
    {
        $user->is_bind = 0;
        $user->phone = null;
        $user->backup_phone = null;
        $user->is_privacy = 1;
        $user->save();
        $user = self::info($user);
        return apiSuccess($user);
    }

    public function get_test_qrcode_details($other_user_id)
    {
        $user = User::where('id', $other_user_id)->find();

        if (empty($user)) {
            return apiError('无效的小程序码');
        }

        if ($user->status == UserCode::STATUS_DISABLE) {
            return apiError('该车主账号被封禁');
        }

        $user = self::info($user);
        return apiSuccess($user);
    }

    //获取微信地图位置
    public function get_wx_map(User $user, $message_id)
    {
        $wechat_message = WechatMessage::find($message_id);
        return apiSuccess($wechat_message);
    }

    //查询奖励列表
    public function get_reward_list(User $user, $status, $limit)
    {

        $where[] = ['user_id', '=', $user->id];
        if ($status) {
            $where[] = ['status', '=', $status];
        }

        $list = UserReward::where($where)->order('created_at', 'desc')->paginate($limit);


        foreach ($list->items() as &$item) {
            if ($item->withdraw_res) {
                $item->withdraw_res = json_decode($item->withdraw_res, true);
            }
            if ($item->order_info) {
                $item->order_info = json_decode($item->order_info, true);
                $item->order_info = $this->handle_order_info($item->order_info);
            }

            //查询和我的关系
            $item->relation = User::where('id', $item['invitee_id'])->value('agent_id') === $user->id ? '下级成员' : '团队成员';

        }
        return apiSuccess($list);
    }

    //处理订单信息
    private function handle_order_info($order_info)
    {
        $order = [
            'order_id' => $order_info['order_id'],//订单号
            'create_time' => date('Y-m-d H:i:s', $order_info['create_time']),//下单时间
            'title' => $order_info['order_detail']['product_infos'][0]['title'],//商品名称
            'thumb_img' => $order_info['order_detail']['product_infos'][0]['thumb_img'],//商品价格
            'pay_time' => date('Y-m-d H:i:s', $order_info['order_detail']['pay_info']['pay_time']),//支付时间
            'status' => $order_info['status'],//订单状态
            'status_text' => WxShopCode::ORDER_STATUS_TEXT[$order_info['status']],//订单状态
        ];
        return $order;
    }


    //申请提现
    public function apply_withdraw(User $user, $id)
    {

        $user_reward = UserReward::find($id);
        if (!empty($user_reward)) {
            $user_reward->withdraw_res = json_decode($user_reward->withdraw_res, true);
            return apiSuccess($user_reward);
        }

        if ($user_reward->status != UserCode::REWARD_STATUS['待入账']) {
            return apiError('状态错误');
        }

        if ($user_reward->user_id != $user->id) {
            return apiError('无效的提现记录');
        }

        //去查一下订单的结算状态
        $order = (new WxShopService())->getWxShopOrder($user_reward->order_id);
        if (empty($order)) {
            Log::error('从小店获取订单失败');
            return false;
        }

        if ($order['status'] != WxShopCode::ORDER_STATUS['完成']) {
            return apiError('订单状态错误');
        }


        $res = (new wx_pay())->transfer($user->openid, $user_reward->order_id, $user_reward->amount * 100);
        if (empty($res['code'])) {
            return apiError($res['msg']);
        }
        $user_reward->withdraw_res = json_decode($user_reward->withdraw_res, true);
        return apiSuccess($user_reward);
    }

    //确认收款
    public function confirm_reward(User $user, $id)
    {
        $user_reward = UserReward::find($id);

        if (empty($user_reward)) {
            return apiError('无效的提现记录');
        }

        $order_id = $user_reward->order_id;

        $res = (new wx_pay())->query($order_id);
        if ($res['code'] == 1) {
            $user_reward->withdraw_res = $res['data'];
            //提现成功
            if ($res['data']['state'] == 'SUCCESS') {
                $user_reward->status = UserCode::REWARD_STATUS['提现成功'];
            } else {
                $user_reward->status = UserCode::REWARD_STATUS['提现失败'];
            }

            $user_reward->save();
        } else {
            return apiError($res['msg']);
        }

        !empty($user_reward->withdraw_res) && $user_reward->withdraw_res = json_decode($user_reward->withdraw_res, true);
        return apiSuccess($user_reward);
    }

    //通过Unionid查询用户
    public static function get_user_by_unionid($unionid)
    {
        return User::where('unionid', $unionid)->find();
    }


    public function statistics(User $user)
    {

        //总奖励
        $total_amount = UserReward::where('user_id', $user->id)->sum('amount');
        //待入账金额
        $pending_amount = UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['待入账'])->sum('amount');
        //待提现金额
        $pending_withdraw_amount = UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['待提现'])->sum('amount');
        //已提现金额
        $withdraw_amount = UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['提现成功'])->sum('amount');
        //售后退款金额
        $refund_amount = UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['订单关闭'])->sum('amount');

        //保留两位小数 不足的要补上
        $total_amount = sprintf("%.2f", $total_amount);
        $pending_amount = sprintf("%.2f", $pending_amount);
        $pending_withdraw_amount = sprintf("%.2f", $pending_withdraw_amount);
        $withdraw_amount = sprintf("%.2f", $withdraw_amount);

        //直属成员
        $total_count = 0;
        //团队成员
        $total_team_count = 0;

        //总下级人数
        $total_sub_count = 0;
        //今日新增下级人数
        $today_sub_count = 0;

        if ($user->is_agent == 1) {
            $total_count = User::where('agent_id', $user->id)->count();
            $total_team_count = User::where('team_id', $user->id)->count();
            $total_sub_count = $total_count + $total_team_count;

            $today_sub_count = User::where(function ($query) use ($user) {
                $query->where('team_id', '=', $user->id)
                    ->whereOr('agent_id', '=', $user->id);
            })
                ->where('join_time', '>', date('Y-m-d'))
                ->count();

            var_dump($today_sub_count);
        } else {
            $total_sub_count = User::where('agent_id', $user->id)->count();
            $today_sub_count = User::where('agent_id', $user->id)->where('join_time', '>', date('Y-m-d'))->count();
        }


        $data = [
            //总奖励
            'total_amount' => $total_amount,
            //待入账金额
            'pending_amount' => $pending_amount,
            //待提现金额
            'pending_withdraw_amount' => $pending_withdraw_amount,
            //已提现金额
            'withdraw_amount' => $withdraw_amount,
            //售后退款金额
            'refund_amount' => $refund_amount,

            //扫码人数
            'scan_count' => UserScan::where('pid', $user->id)->where('user_id', '<>', $user->id)->group('user_id')->count(),
            //今日扫码人数
            'today_scan_count' => UserScan::where('pid', $user->id)->where('user_id', '<>', $user->id)->where('created_at', '>', date('Y-m-d'))->group('user_id')->count(),
            //总下级人数
            'total_sub_count' => $total_sub_count,
            //今日新增下级人数
            'today_sub_count' => $today_sub_count,


            //今日成交订单数
            'today_order_count' => UserReward::where('user_id', $user->id)->where('created_at', '>', date('Y-m-d'))->count(),
            //总成交订单数
            'total_order_count' => UserReward::where('user_id', $user->id)->count(),
            //今日入账订单数
            'today_income_count' => UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['待入账'])->where('created_at', '>', date('Y-m-d'))->count(),
            //总订单退款数
            'total_refund_count' => UserReward::where('user_id', $user->id)->where('status', UserCode::REWARD_STATUS['订单关闭'])->count(),

            //直属成员
            'total_count' => $total_count,
            //团队成员
            'total_team_count' => $total_team_count,
            'is_agent' => $user->is_agent
        ];


        return apiSuccess($data);

    }


    //成员列表
    public function member_list(User $user, $date, $limit)
    {
        $list = User::field('id,nickname,join_time,agent_id,team_id,agent_type')
            ->where(function ($query) use ($user) {
                $query->where('team_id', '=', $user->id)
                    ->whereOr('agent_id', '=', $user->id);
            })
            ->where('join_time', '<=', $date)
            ->order('join_time', 'desc')
            ->paginate($limit);

        foreach ($list->items() as &$item) {
            $item->deal_count = UserReward::where('user_id', $user->id)->where('invitee_id', $item->id)->where('order_status', '<=', UserCode::ORDER_STATUS['已提现'])->count();


            if ($item->agent_type == UserCode::SCAN_TYPE['正式码']) {
                $item->agent_type = '扫描正式挪车码';
            }

            if ($item->agent_type == UserCode::SCAN_TYPE['临时码']) {
                $item->agent_type = '扫描临时挪车码';
            }

            if ($item->agent_type == UserCode::SCAN_TYPE['推广码']) {
                $item->agent_type = '扫描推广码';
            }

            if ($item->agent_type == UserCode::SCAN_TYPE['微信分享']) {
                $item->agent_type = '微信好友分享';
            }

            if ($item->team_id === $user->id) {
                $item->team_id = '团队成员';
            } else {
                $item->team_id = '直属';
            }

            $item->is_agent = $user->is_agent;

        }


        return apiSuccess($list);
    }


    //设置扫码记录
    public function set_scan_record(User $user, $pid, $type, $qrcode)
    {
        $is_new = 0;
        //先查询
        switch ($type) {
            case  UserCode::SCAN_TYPE['正式码']:
                if (empty($qrcode)) {
                    return apiError('无效的二维码');
                }
                if ($pid != $user->id) {
                    $p_user = User::where('id', $pid)->find();
                    if (empty($p_user)) {
                        return apiError('无效的上级');
                    }
                    //判断是否是今天注册的
                    if (empty($user->agent_id) && $user->join_time >= date('Y-m-d')) {
                        $is_new = 1;
                        $user->agent_id = $pid;
                        $user->agent_type = $type;

                        //增加团队成员
                        if (empty($p_user->is_agent)) {
                            //找他的上级
                            $p_p_user = User::where('id', $p_user->agent_id)->find();
                            if ($p_p_user->is_agent) {
                                $user->team_id = $p_p_user->id;
                            }
                        }

                        $user->save();
                    }
                }
                break;
            case  UserCode::SCAN_TYPE['临时码']:
                if ($pid != $user->id) {
                    $p_user = User::where('id', $pid)->find();
                    if (empty($p_user)) {
                        return apiError('无效的上级');
                    }
                    if (empty($user->agent_id) && $user->join_time >= date('Y-m-d')) {
                        $is_new = 1;
                        $user->agent_id = $pid;
                        $user->agent_type = $type;

                        //增加团队成员
                        if (empty($p_user->is_agent)) {
                            //找他的上级
                            $p_p_user = User::where('id', $p_user->agent_id)->find();
                            if ($p_p_user->is_agent) {
                                $user->team_id = $p_p_user->id;
                            }
                        }

                        $user->save();
                    }
                }
                break;
            case  UserCode::SCAN_TYPE['推广码']:
                $agent = Agent::find($pid);
                if (!empty($agent) && $agent->user_id) {
                    $p_user = User::where('id', $agent->user_id)->find();
                    if (empty($p_user)) {
                        return apiError('无效的上级');
                    }
                    //判断是否是今天注册的
                    if (empty($user->agent_id) && $user->join_time >= date('Y-m-d')) {
                        $is_new = 1;
                        $user->agent_id = $p_user->id;
                        $user->agent_type = $type;
                        //增加团队成员
                        if (empty($p_user->is_agent)) {
                            //找他的上级
                            $p_p_user = User::where('id', $p_user->agent_id)->find();
                            if ($p_p_user->is_agent) {
                                $user->team_id = $p_p_user->id;
                            }
                        }


                        $user->save();

                        $agent->push_number = $agent->push_number + 1;
                        $agent->team_number = $agent->team_number + 1;
                        $agent->save();
                    }
                }
                break;
            case  UserCode::SCAN_TYPE['微信分享']:
                if ($pid != $user->id) {
                    $p_user = User::where('id', $pid)->find();
                    if (empty($p_user)) {
                        return apiError('无效的上级');
                    }
                    //判断是否是今天注册的
                    if (empty($user->agent_id) && $user->join_time >= date('Y-m-d')) {
                        $is_new = 1;
                        $user->agent_id = $pid;
                        $user->agent_type = $type;
                        //增加团队成员
                        if (empty($p_user->is_agent)) {
                            //找他的上级
                            $p_p_user = User::where('id', $p_user->agent_id)->find();
                            if ($p_p_user->is_agent) {
                                $user->team_id = $p_p_user->id;
                            }
                        }

                        $user->save();
                    }
                } else {
                    return apiError('自己的微信分享无效');
                }
                break;
            default:
                return apiError('无效的扫码类型');
        }

        /* $p_user = User::where('id', $pid)->find();
         if (empty($p_user)) {
             return apiError('无效的上级');
         }*/


        UserScan::create([
            'user_id' => $user->id,
            'pid' => $pid,
            'type' => $type,
            'qrcode' => $qrcode,
            'is_new' => $is_new
        ]);
        return apiSuccess();
    }

}